#!/bin/bash

apt-get update
sudo apt-get install -y aria2

read -p "输入下载路径(默认：/media/datas/download): " DOWNLOAD_PATH
if [ -z $DOWNLOAD_PATH ]; then
    DOWNLOAD_PATH=/media/datas/download
fi

read -p "输入RPC密钥(如果不输入则不启用RPC): " PASSWD
if [ -z $PASSWD ]; then
    echo "密钥不能为空"
    exit 1
fi

mkdir /etc/aria2
cat > /etc/aria2/aria2.conf << EOF
# 启用 RPC 服务，并允许所有来源访问
enable-rpc=true
rpc-listen-all=true
rpc-allow-origin-all=true

# 如需安全验证，则设置访问密钥（远程调用时须携带 token:your_secret_here）
rpc-secret=$PASSWD

# 下载相关配置
max-concurrent-downloads=5
continue=true
max-connection-per-server=16
split=16

# 指定下载目录与会话文件
dir=$DOWNLOAD_PATH
input-file=/etc/aria2/aria2.session
save-session=/etc/aria2/aria2.session
save-session-interval=60

# 日志文件（便于排查问题）
log=/var/log/aria2.log
EOF

cat > /etc/systemd/system/aria2.service << EOF
[Unit]
Description=Aria2c Download Manager
After=network.target

[Service]
# 根据实际情况选择运行用户，推荐使用专用用户 aria2，若不存在需创建
# User=aria2
# Group=aria2
WorkingDirectory=$DOWNLOAD_PATH
ExecStart=/usr/bin/aria2c --conf-path=/etc/aria2/aria2.conf
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target

EOF

sync

touch /etc/aria2/aria2.session
systemctl enable /etc/systemd/system/aria2.service
# systemctl start aria2.service
